﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Snake.Cache
{
    /// <summary>
    /// 上下文缓存池 Snake的一级缓存
    /// </summary>
    public class ContextPool
    {
        public static ContextPool Instance = new ContextPool();

        private ContextPool() { }

        public void Add(object obj, object id)
        {
            if (obj == null) return;
            String key = CacheKey.getObject(obj.GetType(), id);
            addToContext(key, obj);
        }

        public void AddCount(Type t, int count)
        {
            String key = CacheKey.getCountKey(t);
            addToContext(key, count);
        }

        public void AddCount(Type t, String condition, int count)
        {
            String key = CacheKey.getCountKey(t, condition);
            addToContext(key, count);
        }

        public void AddSqlList(String sql, IList objList)
        {
            addToContext(sql, objList);
        }

        private void addToContext(String key, Object val)
        {
            ContextCache.Put(key, val);
        }


        public object Get<T>(object id)
        {
            var key = CacheKey.getObject(typeof(T).FullName, id);
            return getFromContext(key);
        }

        public IList FindByQuery(Type type, String _queryString, Dictionary<String, Object> _namedParameters)
        {
            return getListFromCache(CacheKey.getQuery(type, _queryString, _namedParameters), type);
        }


        public IList FindBySql(String sql, Type t)
        {
            return ContextCache.Get(sql) as IList;
        }

        public int FindCount(Type t)
        {
            String key = CacheKey.getCountKey(t);
            Object obj = getFromContext(key);
            return obj == null ? -1 : (int)obj;
        }

        public int FindCount(Type t, String condition)
        {
            String key = CacheKey.getCountKey(t, condition);
            Object obj = getFromContext(key);
            return obj == null ? -1 : (int)obj;
        }

        //---------------------------------------------------

        private static Object getFromContext(String key)
        {
            Object obj = ContextCache.Get(key);
            return obj;
        }


        private static IList getListFromCache(String queryKey, Type t)
        {
            return getFromContext(queryKey) as IList;
        }

        public void Delete(Type t, int id)
        {
            ContextCache.Remove(t.FullName, id);
        }
    }
}
